//
//  CAIImagePickerControllerKit.m
//  CAIImagePickerController
//
//  Created by 海参 on 2021/8/24.
//

#import "CAIImagePickerControllerKit.h"
#import "TZImagePickerController.h"
#import "CAIImageLocationManager.h"





@interface CAIImagePickerControllerKit ()<ZXUIImagePickerManagerDelegate,CAIPHPickerControllerManagerDelegate>


@property (nonatomic, strong) ZXUIImagePickerManager *imagePickerVCManager;

@property (nonatomic, strong) CAIPHPickerControllerManager *phPickerControllerManager API_AVAILABLE(ios(14.0));


@property (nonatomic, strong) TZImagePickerController *imagePickerController;

@end

@implementation CAIImagePickerControllerKit

+ (instancetype)shareInstance
{
    static id instance = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

///要dismiss后才会释放
- (void)dealloc{
    
}



- (ZXUIImagePickerManager *)imagePickerVCManager
{
    if (!_imagePickerVCManager) {
        ZXUIImagePickerManager *manager = [[ZXUIImagePickerManager alloc] init];
        manager.delegate = self;
        _imagePickerVCManager = manager;
    }
    return _imagePickerVCManager;
}

- (CAIPHPickerControllerManager *)phPickerControllerManager
{
    if (!_phPickerControllerManager) {
        CAIPHPickerControllerManager *manager = [[CAIPHPickerControllerManager alloc] init];
        _phPickerControllerManager = manager;
    }
    return _phPickerControllerManager;
}

- (TZImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
        TZImagePickerController *vc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 columnNumber:4 delegate:nil];
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        _imagePickerController = vc;
    }
    return _imagePickerController;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



/// 弹出相册选择-选择图片
/// @param delegate 代理
/// @param viewController presentingViewController
- (void)showImagePickerWithFromViewController:(UIViewController *)viewController
                                     delegate:(id<CAIImagePickerControllerKitDelegate>)delegate
                               maxImagesCount:(NSInteger)maxImagesCount
{
    [self showImagePickerWithFromViewController:viewController
                                       delegate:delegate
                                 maxImagesCount:maxImagesCount
                      allowPickingOriginalPhoto:YES
                               allowTakePicture:YES
                              allowPickingImage:YES
                              allowPickingVideo:NO];
}


- (void)showImagePickerWithFromViewController:(UIViewController *)viewController
                                     delegate:(id<CAIImagePickerControllerKitDelegate>)delegate
                               maxImagesCount:(NSInteger)maxImagesCount
                    allowPickingOriginalPhoto:(BOOL)allowPickingOriginalPhoto
                             allowTakePicture:(BOOL)allowTakePicture
{
    [self showImagePickerWithFromViewController:viewController
                                       delegate:delegate
                                 maxImagesCount:maxImagesCount
                      allowPickingOriginalPhoto:allowPickingOriginalPhoto
                               allowTakePicture:allowTakePicture
                              allowPickingImage:YES
                              allowPickingVideo:NO];
}

- (void)showImagePickerWithFromViewController:(UIViewController *)viewController
                                     delegate:(id<CAIImagePickerControllerKitDelegate>)delegate
                               maxImagesCount:(NSInteger)maxImagesCount
                    allowPickingOriginalPhoto:(BOOL)allowPickingOriginalPhoto
                             allowTakePicture:(BOOL)allowTakePicture
                            allowPickingImage:(BOOL)allowPickingImage
                            allowPickingVideo:(BOOL)allowPickingVideo
{
    CAIPickerConfiguration *configuration = [CAIPickerConfiguration new];
    configuration.maxImagesCount = maxImagesCount;
    configuration.allowPickingImage = allowPickingImage;
    configuration.allowPickingOriginalPhoto = allowPickingOriginalPhoto;
    configuration.allowPickingVideo = allowPickingVideo;
    configuration.allowTakePicture = allowTakePicture;
    [self showImagePickerWithFromViewController:viewController delegate:delegate configuraton:configuration];
}

- (void)showImagePickerWithFromViewController:(UIViewController *)viewController
                                     delegate:(id<CAIImagePickerControllerKitDelegate>)delegate
                                 configuraton:(nullable CAIPickerConfiguration *)configuration
{
    self.caiPickerDelegate = delegate;
    if (!configuration) {
        configuration = [CAIPickerConfiguration new];
    }
    
    if (@available(iOS 14, *)) {
        if (!configuration.allowTakePicture) {
            [self.phPickerControllerManager showImagePickerWithFromViewController:viewController
                                                                         delegate:self
                                                                   selectionLimit:configuration.maxImagesCount
                                                                allowPickingImage:configuration.allowPickingImage
                                                                allowPickingVideo:configuration.allowPickingVideo];
            return;
        }
    }
    self.imagePickerController.maxImagesCount = configuration.maxImagesCount;
    //初始化多选择照片
    self.imagePickerController.pickerDelegate = self;
    //是否有选择原图
    self.imagePickerController.allowPickingOriginalPhoto = configuration.allowPickingOriginalPhoto;
    //用户选中的图片
//    imagePicker.selectedAssets = self.selectedAssets;
    //是否允许选择视频
    self.imagePickerController.allowPickingVideo = configuration.allowPickingVideo;
    //是否可以选择图片,如果不可以，则拍照也不可以，不要用这个属性；
    self.imagePickerController.allowPickingImage = configuration.allowPickingImage;
    //拍照
    self.imagePickerController.allowTakePicture = configuration.allowTakePicture;
    [viewController presentViewController:self.imagePickerController animated:YES completion:^{}];
}



//+ (void)showCameraControllerWithSourceController:(UIViewController *)sourceController
//                                        delegate:(id<CAIImagePickerControllerKitDelegate>)delegate
//{
//    [self showCameraControllerWithSourceController:sourceController delegate:delegate allowsEditing:NO];
//}
//
//+ (void)showCameraControllerWithSourceController:(UIViewController *)sourceController
//                                        delegate:(id<CAIImagePickerControllerKitDelegate>)delegate
//                                   allowsEditing:(BOOL)allowsEditing
//{
//    CAIImagePickerControllerKit *kit = [CAIImagePickerControllerKit shareInstance];
//    [kit showCameraControllerWithSourceController:sourceController delegate:delegate allowsEditing:allowsEditing];
//}

- (void)showCameraControllerWithSourceController:(UIViewController *)sourceController
                                        delegate:(id<CAIImagePickerControllerKitDelegate>)delegate
{
    [self showCameraControllerWithSourceController:sourceController delegate:delegate allowsEditing:NO];
}

- (void)showCameraControllerWithSourceController:(UIViewController *)sourceController
                                        delegate:(id<CAIImagePickerControllerKitDelegate>)delegate
                                   allowsEditing:(BOOL)allowsEditing
{
    self.caiPickerDelegate = delegate;
    self.imagePickerVCManager.allowsEditing = allowsEditing;
    [self.imagePickerVCManager presentCameraPhotoWithSourceController:sourceController];
}


- (void)showCameraMultiPhotoWithSourceController:(UIViewController *)sourceController
                                        delegate:(id<CAIImagePickerControllerKitDelegate>)delegate
                                 maxTakePhotoNum:(NSInteger)maxTakePhotoNum{
    self.caiPickerDelegate = delegate;
    self.imagePickerVCManager.watermask = self.watermask;
    [self.imagePickerVCManager presentCameraMultiPhotoWithSourceController:sourceController maxTakePhotoNum:maxTakePhotoNum];
}

- (void)dismissCamera{
    [self.imagePickerVCManager dismissCamera];
}

#pragma mark -

+ (void)setLocation:(NSString *)location{
    [CAIImageLocationManager shareInstance].location = location?location:@"未获取到有效定位信息";
}


#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    
    [self didFinishPickingPhotos:photos sourceAssets:assets errorWithCode:ImagePickerControllerErrorCodeNOError];
}

- (void)caiImagePickerControllerDidCancel:(TZImagePickerController *)picker{
    [self didFinishPickingPhotos:nil sourceAssets:nil errorWithCode:ImagePickerControllerErrorCodeCancel];
}

- (void)didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets errorWithCode:(ImagePickerControllerErrorCode)code
{
    if (photos) {
        if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:error:)]) {
            [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:photos sourceAssets:assets error:nil];
        }
        else if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:)]) {
            [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:photos sourceAssets:assets];
        }
    }else{
        
        NSError *error = [CAIImagePickerManagerErrorConst errorWithCode:code];
        if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:error:)]) {
            [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:nil sourceAssets:nil error:error];
        }
    }
    self.imagePickerController = nil;
}

#pragma mark - ImagePickerVCManagerDelegate

- (void)imagePickerControllerManager:(ZXUIImagePickerManager *)manager didFinishPickingImageWithInfo:(NSDictionary<NSString *,id> *)info image:(UIImage *)image error:(NSError *)error
{
    NSArray *photos = nil;
    if (image) {
        photos = @[image];
    }
    if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:error:)]) {
        [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:photos sourceAssets:nil error:error];
    }
    else if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:)] && !error) {
        [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:photos sourceAssets:nil];
    }
}


- (void)imagePickerControllerManager:(ZXUIImagePickerManager *)manager didFinishPickingLivePhoto:(PHLivePhoto *)livePhoto image:(UIImage *)image error:(NSError *)error API_AVAILABLE(ios(9.1)){
    
    NSArray *photos = nil;
    if (image) {
        photos = @[image];
    }
    if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:error:)]) {
        [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:photos sourceAssets:nil error:error];
    }
    else if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:)] && !error) {
        [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:photos sourceAssets:nil];
    }
}

///不能清除对象，有点击确认选择后，依然要使用图片选择控制器的场景；
- (void)imagePickerControllerManager:(ZXUIImagePickerManager *)manager
              didFinishPickingImages:(NSArray<UIImage *> *)images
                         imageModels:(NSArray<CAIUIImagePickerCameraPhotoModel *> *)models
                               error:(NSError *)error
{
    if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:error:)]) {
        [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:images sourceAssets:models error:error];
    }
    else if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:)] && !error) {
        [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:images sourceAssets:models];
    }
}


# pragma mark - CAIPHPickerControllerManagerDelegate

- (void)imagePickerControllerManager:(nonnull CAIPHPickerControllerManager *)manager didFinishPickingMediaWithPhotos:(nullable NSArray<UIImage *> *)photos error:(nullable NSError *)error API_AVAILABLE(ios(14))
{
    if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:error:)]) {
        [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:photos sourceAssets:nil error:error];
    }
    else if ([self.caiPickerDelegate respondsToSelector:@selector(imagePickerController:didFinishPickingPhotos:sourceAssets:)] && !error) {
        [self.caiPickerDelegate imagePickerController:self didFinishPickingPhotos:photos sourceAssets:nil];
    }
    self.phPickerControllerManager = nil;
}




@end
